package com.longnuoqi.mydoctor.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.entity.User;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.EncodeDecodeUtil;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;


import java.sql.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2016/1/12.
 */
public class UserProfileEditActivity extends AppCompatActivity {
    private ImageView back;
    private EditText name;
    private RadioButton male;
    private RadioButton female;
    private RadioButton secret;
    private EditText birth;
    private EditText city;
    private EditText sign;
    private RelativeLayout save;

    private User user;
    private String nameV;
    private int genderV;
    private Date birthV;
    private String cityV;
    private String signV;

    private SharedPreferences sharedPreferences;
    private String access_token;
    private String url;
    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(UserProfileEditActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_profile_edit_layout);
        ActivityCollection.addActivity(this);
        Intent intent = getIntent();
        user = intent.getParcelableExtra("user");
        initView();
        initData();
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.user_pro_back_btn);
        save = (RelativeLayout) findViewById(R.id.user_pro_save_btn);
        back.setOnClickListener(onClickListener);
        save.setOnClickListener(onClickListener);

        name = (EditText) findViewById(R.id.user_pro_name_text);
        male = (RadioButton) findViewById(R.id.user_pro_gender_male);
        female = (RadioButton) findViewById(R.id.user_pro_gender_female);
        secret = (RadioButton) findViewById(R.id.user_pro_gender_secret);
        birth = (EditText) findViewById(R.id.user_pro_birth_text);
        city = (EditText) findViewById(R.id.user_pro_home_text);
        sign = (EditText) findViewById(R.id.user_pro_sign_text);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_pro_back_btn:
                    Intent intent = getIntent();
                    setResult(1, intent);
                    finish();
                    break;
                case R.id.user_pro_save_btn:
                    saveData();
                    break;
                default:
                    break;
            }
        }
    };

    private void initData() {
        if (user.getGender() == 1) {
            male.setChecked(true);
        } else if (user.getGender() == 0) {
            female.setChecked(true);
        } else {
            secret.setChecked(true);
        }
        name.setText(user.getAccount());
        birth.setText(FileUtil.dateFormat(user.getBirth()));
        city.setText(user.getCity());
        sign.setText(user.getSignature());
    }


    public void saveData() {
        if (male.isChecked()) {
            genderV = 1;
        } else if (female.isChecked()) {
            genderV = 0;
        } else if (secret.isChecked()) {
            genderV = -1;
        } else {
            genderV = 0;
        }
        nameV = EncodeDecodeUtil.encoderUtf8(name.getText().toString().trim());
        birthV = Date.valueOf(birth.getText().toString());
        cityV = EncodeDecodeUtil.encoderUtf8(city.getText().toString().trim());
        signV = EncodeDecodeUtil.encoderUtf8(sign.getText().toString());


        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        access_token = sharedPreferences.getString("access_token", "");
        url = "http://www.tngou.net/api/user/profile?access_token=" + access_token + "&account=" +
                nameV + "&gender=" + genderV + "&city=" + cityV + "&signature=" + signV + "&birth=" + birthV;
        RequestQueue queue = Volley.newRequestQueue(UserProfileEditActivity.this);
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.e("===================", "url:" + url);
                Log.e("===================", "s:" + s);
                Intent intent = getIntent();
                setResult(2, intent);
                finish();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }


}
